<template>
  <div>
    <div class="nav">
      <img class="exitImg" src="@/assets/icons/png/exit.png" @click="exit"/>
      <div class="title">消息</div>
      <!--   空白块 为了实现居中效果   -->
      <div style="width: 45px"></div>
    </div>
    <div class="message-container">
      <message-item
          v-for="(message, index) in messages"
          :key="index"
          :message="message"
          :is-new="isNewMessage(message)"
          @scroll="handleScroll"
      ></message-item>
    </div>
  </div>
</template>

<script>
import router from "@/router";
import MessageItem from './MessageItem.vue';
import messageApi from "@/api/messageApi";
export default {
  components: {
    MessageItem,
  },
  data() {
    return {
      messages: [],
      messageType:"",
    }
  },
  created() {
    this.queryMessages();

  },
  mounted() {

  },
  methods: {
    exit() {
      router.push("/message");
    },
    isNewMessage(message) {
      return Date.now() - message.messageUpdateTime < 5 * 60 * 1000;
    },
    queryMessages() {
      const param = {
        userId: window.localStorage.getItem("userId"),
        messageType: this.$route.params.messageType
      }
      messageApi.queryMessage(param).then((res) => {
        if (res.data.code == 200) {
          let data = res.data.data;
          for (let i = 0; i < data.length; i++) {
            if (data[i].messageUpdateTime != "") {
              let date1 = data[i].messageUpdateTime.substring(0,10);
              let date2 = data[i].messageUpdateTime.substring(11,16);
              data[i].messageUpdateTime = date1 +" " + date2;
            }
          }
          this.messages = data;
        }
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      })
    },
    scrollToBottom() {
      const container = this.$el.querySelector('.message-container');
      container.scrollTop = container.scrollHeight;
    },
    handleScroll(event) {
      const container = event.target;
      if (container.scrollTop === 0) {
        // 滚动到顶部，可能是新消息到来
        this.scrollToBottom();
      }
    },
  }

}

</script>

<style scoped>
.nav {
  width: 100%;
  height: 80px;
  background-color: rgb(251, 219, 68);
  display: flex; /* 使用flex布局使子元素水平排列 */
  align-items: center; /* 垂直居中对齐子元素 */
  justify-content: flex-start; /* 水平居左对齐子元素 */
}

.exitImg {
  width: 25px;
  height: 25px;
  margin-left: 20px;
}

.title {
  margin: auto; /* 自动调整左侧间距，使文本居中 */
}
.message-container {
  height: 100%; /* 消息容器的高度 */
  overflow-y: auto; /* 启用滚动条 */
  scroll-behavior: smooth; /* 滚动行为设置为平滑 */
}
</style>